/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.imagepipeline.producers;

import com.facebook.common.memory.PooledByteBufferFactory;
import com.facebook.common.util.UriUtil;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.annotation.Nullable;
import com.oszc.bbhmlibrary.utils.LogUtil;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.data.resultset.ResultSet;
import ohos.utils.net.Uri;

import java.io.*;
import java.util.concurrent.Executor;

/**
 * Represents a local content Uri fetch producer.
 */
public class LocalContentUriFetchProducer extends LocalFetchProducer {
     private final String TAG = LocalContentUriFetchProducer.class.getSimpleName();

    public static final String PRODUCER_NAME = "LocalContentUriFetchProducer";

    private static final String[] PROJECTION =
            // new String[] {MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.DATA};
            new String[]{"_id", "_data"};

    // private final ContentResolver mContentResolver;
    private final DataAbilityHelper mContentResolver;

    public LocalContentUriFetchProducer(
            Executor executor,
            PooledByteBufferFactory pooledByteBufferFactory,
            DataAbilityHelper contentResolver) {
        super(executor, pooledByteBufferFactory);
        mContentResolver = contentResolver;
    }

    @Override
    protected EncodedImage getEncodedImage(ImageRequest imageRequest) throws IOException, DataAbilityRemoteException {
        Uri uri = imageRequest.getSourceUri();
        if (UriUtil.isLocalContactUri(uri)) {
            final InputStream inputStream;
            try {
                if (uri.toString().endsWith("/photo")) {
                    FileDescriptor fileDescriptor = mContentResolver.openFile(uri, "r");
                    inputStream = new FileInputStream(fileDescriptor);
                } else if (uri.toString().endsWith("/display_photo")) {
                    FileDescriptor fd = mContentResolver.openFile(uri, "r");
                    inputStream = new FileInputStream(fd);

                } else {
                    //inputStream = ContactsContract.Contacts.openContactPhotoInputStream(mContentResolver, uri);
                    ResultSet cursor = mContentResolver.query(uri,
                            new String[]{"data15"}, null);
                    try {
                        if (cursor == null || !cursor.goToNextRow()) {
                            return null;
                        }
                        byte[] data = cursor.getBlob(0);
                        if (data == null) {
                            return null;
                        }
                        inputStream = new ByteArrayInputStream(data);
                        if (inputStream == null) {
                            throw new IOException("Contact photo does not exist: " + uri);
                        }
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
            } catch (IOException | DataAbilityRemoteException e) {
                throw new IOException("Contact photo does not exist: " + uri);
            }
            // If a Contact URI is provided, use the special helper to open that contact's photo.
            return getEncodedImage(inputStream, EncodedImage.UNKNOWN_STREAM_SIZE);
        } else if (UriUtil.isLocalCameraUri(uri)) {
            EncodedImage cameraImage = getCameraImage(uri);
            if (cameraImage != null) {
                return cameraImage;
            }
        }
        return getEncodedImage(new FileInputStream(mContentResolver.openFile(uri, "r")), EncodedImage.UNKNOWN_STREAM_SIZE);
    }

    private @Nullable
    EncodedImage getCameraImage(Uri uri) throws IOException, DataAbilityRemoteException {
        LogUtil.error(TAG,"getCameraImage");
        ResultSet cursor = mContentResolver.query(uri, PROJECTION, null);
        if (cursor == null) {
            return null;
        }
        try {
            if (cursor.getRowCount() == 0) {
                return null;
            }
            cursor.goToFirstRow();

            final String pathname =
                    cursor.getString(cursor.getColumnIndexForName("_data"));
            if (pathname != null) {
                FileDescriptor fd = mContentResolver.openFile(uri, "r");
                return getEncodedImage(new FileInputStream(fd), getLength(pathname));
            }
        } finally {
            cursor.close();
        }
        return null;
    }

    private static int getLength(String pathname) {
        return pathname == null ? -1 : (int) new File(pathname).length();
    }

    @Override
    protected String getProducerName() {
        return PRODUCER_NAME;
    }
}
